<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="obj.name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="obj.age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="obj.gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add(obj1.id)">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in arr" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="remove(item.id)">删除</button>
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
// 一定一定要记得 数据驱动视图
export default {
  data() {
    return {
      isAdd: false,
      arr: [],
      obj: {
        id: +new Date(),
        name: "",
        age: "",
        gender: "男",
      },
      obj1: {},
    }
  },
  methods: {
    add(id) {
      if (this.isAdd) {
        this.arr.map((item, i) => {
          if (item.id === id) {
            this.arr.splice(i, 1, { ...this.obj })
          }
        })
      } else {
        this.obj1 = { ...this.obj }
        this.arr.push(this.obj1)
      }
      this.isAdd = false
      this.obj = {
        id: +new Date(),
        name: "",
        age: "",
        gender: "男",
      }
    },
    remove(id) {
      this.arr.splice(
        this.arr.findIndex((item) => item.id === id),
        1
      )
    },
    edit(id) {
      this.isAdd = true
      this.arr.map((item) => {
        if (item.id === id) {
          this.obj = { ...item }
        }
      })
    },
  },
}
</script>
